<template>
	<view class="page">
		<view class="title">
			<textarea :value="url" maxlength="-1" @input="inputUrl" placeholder="请输入链接" />
			<view class="title-confirm" @click="queryUid">发送</view>
		</view>
		<view style="display: flex; justify-content: center;margin-top: 10rpx; color: #999;" @click="toGetUrlDirections">不知道如何获取链接，请戳这里</view>
		<view v-if="gachaInfo.length > 0" class="uni-list" style="margin-top: 20rpx;">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					选择UID
				</view>
				<view class="uni-list-cell-db">
					<picker @change="bindPickerUidChange" :value="uidIndex" :range="uidList">
						<view class="uni-input">{{uidList[uidIndex]}}</view>
					</picker>
				</view>
			</view>
		</view>
		<view v-if="gachaInfo.length > 0" class="uni-list" style="margin-top: 20rpx;">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					选择卡池
				</view>
				<view class="uni-list-cell-db">
					<picker @change="bindPickerGachaChange" :value="gachaIndex" :range="gachaList" range-key="remark">
						<view class="uni-input">{{gachaList[gachaIndex].remark}}</view>
					</picker>
				</view>
			</view>
		</view>
		<view v-if="achievements" style="margin-top: 20rpx; fost-size:26rpx;font-weight: 600;">
			查询结果
		</view>
		<view v-if="achievements" style="margin-top: 20rpx;">
			<text v-for="(item,index) in achievements.ups" :key="index" style="margin-right: 5rpx;" :style="{color: colorList[index]}">
				{{item.data.name}}[{{item.nowNum}}]
			</text>
		</view>
		<view v-if="achievements">当前已<text style="color: red;">{{achievements.nowNum}}</text>抽未出金,下抽出金概率<text style="color: gold;">{{queryGoldProbability()}}</text></view>
		<view class="charts-box" v-if="chartData.series.length > 0" style="margin-top: 20rpx;">
		  <qiun-data-charts
		    type="pie"
		    :chartData="chartData"
			:opts="opts"
		    background="none"
		  />
		</view>
	</view>
</template>

<script>
	// import { get, post } from '../../API/index.js';
	import { getEndId, queryLog, asyncApplet, statistic, querygachaType} from '../../API/api.js'
	import { setClipboardData, getClipboardData } from '@/uni_modules/u-clipboard/js_sdk';
	export default {
		data() {
			return {
				url: '',
				uidList: [],
				uidIndex: 0,
				gachaList: [],
				gachaIndex: '',
				gachaInfo: [],
				achievements: null,
				colorList: [],
				opts: {},
				chartData:{
				  categories:[],
				  series: []
				},
				authkey: '',
			}
		},
		async created() {
			const gachaInfo = uni.getStorageSync('gachaInfo');
			getClipboardData().then((data) => {
				console.log('res-qqqqqqqqqqqqq',data)
				if (/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(data)) {
					this.url = data
				}
			})
			const res = await querygachaType()
			console.log('res', res)
			if (res.code == 0) {
				this.gachaList = res.data
			}
			if (gachaInfo) {
				console.log('gachaInfo', gachaInfo)
				const uidList = []
				gachaInfo.forEach(item => {
					uidList.push(item.uid)
				})
				this.uidList = uidList
				this.gachaInfo = gachaInfo
				
			}
		},
		methods: {
			querygachaList(gacha_type, authkey ,lastId, cb, gachaInfoList = [], endId = 0) {
				  setTimeout(async () => {
					  const res = await queryLog(gacha_type, authkey, endId);
					  console.log('____res', res)
					  if (res.retcode == 0 && res.data.list.length > 0) {
						gachaInfoList.push(...res.data.list)
					  }
					  if(res.data.list.length < 20 || endId == res.data.list[res.data.list.length - 1].id || res.data.list.findIndex(item => item.id == lastId) != -1){
						  console.log('cb(gachaInfoList)', gachaInfoList)
						cb(gachaInfoList)
					  } else {
						this.querygachaList(gacha_type, authkey ,lastId, cb, gachaInfoList, res.data.list[res.data.list.length - 1].id)
					  }
				  }, 300)
			},
			
			querygachaListPromise(gacha_type, authkey, lastId) {
				return new Promise((resolve, reject) => {
					this.querygachaList(gacha_type, authkey, lastId, resolve)
				})
			},
			
			async queryUid() {
				uni.showLoading({
					title:'查询中...'
				})
				try{
				  // 正则表达式 IOS不支持零断言
				  let authkey__ = /authkey=(.*?)&/.exec(this.url)[0];
				  let authkey_ = authkey__.replace(/authkey=/, "");
				  let authkey = authkey_.replace(/&/, "");
				  this.authkey = authkey;
				  const res = await queryLog('301', authkey)
				  const uid = res.data.list[0].uid
				  const i = this.uidList.findIndex(item => item == uid)
				  if (i == -1) {
					  this.uidList.push(uid)
					  this.uidIndex = this.uidList.length - 1
				  } else {
					  this.uidIndex = this.uidList[i]
				  }
				  const _res = await getEndId(uid)
				  if (_res.code == 0) {
					  const up = _res.data.find(item => /角色/.test(item.gachaType.remark))
					  const ups = await this.querygachaListPromise('301', authkey, up.endId)
					  
					  const weapon = _res.data.find(item => /武器/.test(item.gachaType.remark))
					  const weapons = await this.querygachaListPromise('302', authkey, weapon.endId)
					  
					  const usually = _res.data.find(item => /常驻/.test(item.gachaType.remark))
					  const usuallys = await this.querygachaListPromise('200', authkey, usually.endId)
					  
					  const rookie = _res.data.find(item => /新手/.test(item.gachaType.remark))
					  const rookies = await this.querygachaListPromise('100', authkey, rookie.endId)
					  
					  // const res = await Promise.all([
						 //  this.querygachaListPromise('301', authkey, up.endId),
						 //  this.querygachaListPromise('302', authkey, weapon.endId),
						 //  this.querygachaListPromise('200', authkey, usually.endId),
						 //  this.querygachaListPromise('100', authkey, rookie.endId)
					  // ])
					  // console.log(')
					const data = [
							...weapons,
							...ups,
							...rookies,
							...usuallys
						]
						console.log('data', data)
						
						const asyncGacha = await asyncApplet(data)
						console.log('asyncGacha', asyncGacha)
						console.log('uid', uid);
						const statisticData = await statistic(uid);
						console.log('statisticData', statisticData)
						if (statisticData.code == 0) {
							const i = this.gachaInfo.findIndex(item => item.uid == uid)
							console.log('i', i)
							if (i == -1) {
								this.gachaInfo.push({
									uid,
									data: statisticData.data
								})
							} else {
								this.$set(this.gachaInfo, i, {
									uid,
									data: statisticData.data
								})
							}
							console.log('this.gachaInfo', this.gachaInfo)
							uni.setStorageSync('gachaInfo', this.gachaInfo)
							uni.hideLoading()
						}
						
				  }
				}
				catch(err){
					console.log('err', err)
					uni.hideLoading()
				  uni.showToast({
					title: '链接错误',
					icon: 'error'
				  });
				  let temp = await new Promise(function(resolve, reject) {
					setTimeout(function(){
					  uni.hideToast({
						success: (res) => {
						  return 0;
						},
					  })
					}, 2000);
				  })
				}
			},
			queryGoldProbability() {
				let isWeapons = false;
				if (/武器/.test(this.gachaList[this.gachaIndex].name)) {
					isWeapons = true;
				}
				return this.computeProbability(isWeapons)
			},
			computeProbability(type) {
				const number = this.achievements.nowNum
				if (type) {
					if (number < 63) {
						return `${0.007 * 100}%`
					} else if (number == 63) {
						return `${0.039 * 100}%`
					} else {
						let probability = (((number - 63) / 17 * 0.993) + 0.007) * 100
						return `${probability}%`
					}
				} else {
					if (number <= 73) {
						return `${0.006 * 100}%`
					} else {
						let probability = (((number - 73) / 17 * 0.994) + 0.006) * 100
						return `${probability}%`
					}
				}
			},
			randonColor() {
				return `rgb(${this.randomNum(0,255)}, ${this.randomNum(0,255)}, ${this.randomNum(0,255)})`
			},
			randomNum(minNum,maxNum){ 
			    switch(arguments.length){ 
			        case 1: 
			            return parseInt(Math.random()*minNum+1,10); 
			        break; 
			        case 2: 
			            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
			        break; 
			            default: 
			                return 0; 
			            break; 
			    } 
			} ,
			bindPickerUidChange(e) {
				this.uidIndex = e.detail.value
				this.queryAchievements()
			},
			bindPickerGachaChange(e) {
				this.gachaIndex = e.detail.value
				this.queryAchievements()
			},
			queryAchievements() {
				if (this.uidIndex === '') {
					uni.showToast({
						icon:'error',
						title: '选个UID'
					})
					return
				}
				if (this.gachaIndex === '') {
					uni.showToast({
						icon:'error',
						title: '选个卡池'
					})
					return
				}
				let achievements;
				console.log('this.gachaInfo', this.gachaInfo)
				console.log('this.gachaList', this.gachaList)
				console.log('this.uidList[this.uidIndex]', this.uidList[this.uidIndex])
				this.gachaInfo.forEach(item => {
					if (item.uid == this.uidList[this.uidIndex]) {
						item.data.forEach(_item => {
							if (JSON.stringify(_item.gachaType.codes) == JSON.stringify(this.gachaList[this.gachaIndex].codes)) {
								achievements = _item
							}
						})
					}
				})
				console.log('achievements', achievements)
				if (achievements) {
					
					const data = []
					achievements.ranks.forEach(item => {
						data.push({
							name: `${item.rankType.remark}`,
							value: item.number * 1
						})
					})
					console.log('data', data)
					console.log('this.chartData', this.chartData)
					this.$set(this.chartData, 'series', [
						{
							data
						}
					])
					const _data = [];
					achievements.ranks.forEach(item => {
						switch (item.rankType.code) {
						  case 3:
							_data.push('#48feff');
							break;
						  case 4:
							_data.push('#c577ef');
							break;
						  case 5:
							_data.push('#ffb253');
							break;
						  default:
							break;
						}
					})
					console.log('_data', _data)
					this.$set(this.opts, "color", _data);
					this.achievements = achievements;
					const colorList = []
					this.achievements.ups.forEach(item => {
						colorList.push(this.randonColor())
					})
					this.colorList = colorList
				} else {
					this.achievements = null;
					// uni.showModal({
					// 	content: '寄，查询卡池出错了，发群里找人修BUG',
					// 	showCancel: false,
					// })
				}
			},
			toGetUrlDirections() {
				uni.navigateTo({
					url: '../getUrlDirections/getUrlDirections'
				})
			},
			getData(res) {
				// const uidList = new Set(...this.uidList, res.uid)
				const gachaInfo = this.gachaInfo
				const i = this.gachaInfo.findIndex(item => item.uid == res.uid)
				if (i == -1) {
					gachaInfo.push(res)
				} else {
					gachaInfo[i] = res
				}
				uni.setStorageSync('gachaInfo', gachaInfo)
				this.gachaInfo = gachaInfo
				const uidList = []
				gachaInfo.forEach(item => {
					uidList.push(item.uid)
				})
				this.uidList = uidList
			},
			inputUrl(e) {
				console.log('e', e)
				this.url = e.detail.value
			},
			bindPickerChange(e) {
				console.log('e', e)
			}
		}
	}
</script>

<style scoped lang="scss">
.page {
	background-color: #eee;
	min-height: 100vh;
	min-width: 100vw;
	padding: 10rpx;
	.title {
		display: flex;
		align-items: center;
		textarea {
			width: 570rpx;
			background-color: #FFF;
			height: 66rpx;
			border-radius: 10rpx;
			padding-left: 10rpx;
			margin-right: 10rpx;
		}
		.title-confirm {
			width: 120rpx;
			height: 66rpx;
			border-radius: 10rpx;
			background-color: #409EFF;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #FFF;
			font-size: 28rpx;
		}
	}
	/* 请根据需求修改图表容器尺寸，如果父容器没有高度图表则会显示异常 */
	.charts-box{
	  width: 100%;
	  height:300px;
	}
}
</style>